package mil.af.amc.adpetracker.dao.hibernate;

import mil.af.amc.adpetracker.dao.ManufacturerDao;
import mil.af.amc.adpetracker.model.EquipmentType;
import mil.af.amc.adpetracker.model.ItemModel;
import mil.af.amc.adpetracker.model.Manufacturer;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Hibernate Manufacturer DAO implementation
 *
 * @author TSgt Jason Ferguson
 */
@Service("manufacturerDao")
public class HibernateManufacturerDao extends HibernateGenericDao<Manufacturer> implements ManufacturerDao {

    public HibernateManufacturerDao() {
        super(Manufacturer.class);
    }

    @SuppressWarnings({"unchecked", "ForLoopReplaceableByForEach"})
    public List<Manufacturer> getManufacturerByEquipmentType(EquipmentType type) {

        DetachedCriteria crit = DetachedCriteria.forClass(ItemModel.class);
        DetachedCriteria typeCrit = crit.createCriteria("type");
        typeCrit.add(Restrictions.eq("id", type.getId()));
        List<ItemModel> modelList = (List<ItemModel>) getHibernateTemplate().findByCriteria(crit);

        List<Manufacturer> manufacturerList = new ArrayList<Manufacturer>();
        for (Iterator<ItemModel> it = modelList.iterator(); it.hasNext();) {
            ItemModel model = it.next();
            if (!manufacturerList.contains(model.getManufacturer())) {
                Manufacturer manu = model.getManufacturer();
                if (manu!=null && manu.getName() != null) {
                    manufacturerList.add(model.getManufacturer());
                }
            }
        }

        Collections.sort(manufacturerList);
        return manufacturerList;

    }
}
